package com.example.concurrent.demo.executor;

import com.example.concurrent.demo.runnable.MyRunnable;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author susc
 * @title: ThreadPoolExcutorDemo
 * @projectName concurrent-demo
 * @description: TODO
 * @date 2021/9/2810:24
 */
public class ThreadPoolExcutorDemo {
    /**
     * 核心线程数
      */
    private static final int CORE_POOL_SIZE = 5;
    /**
     * 最大线程数
      */
    private static final int MAX_POOL_SIZE = 10;
    /**
     * 任务队列容量
      */
    private static final int QUEUE_CAPACITY = 100;
    /**
     * 等待时间为1L
     */
    private static final Long KEEP_ALIVE_TIME = 1L;

    public static void main(String[] args) {
        // 使用阿里巴巴推荐的创建线程池的方式
        TimeUnit unit;
        BlockingQueue workQueue;
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, new ArrayBlockingQueue<>(QUEUE_CAPACITY)
        , new ThreadPoolExecutor.CallerRunsPolicy());

        for(int i = 0; i < 10; i++){
            // 创建WorkThread对象（WorkerThread类实现了Runnable接口）
            Runnable worker = new MyRunnable("" + i);
            // 执行runnable
            executor.submit(worker);
        }
        // 终止线程池
        executor.shutdown();
        while (!executor.isTerminated()){

        }
        System.out.println("finished all threads");
    }

}
